package com.java.springcloud.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.springframework.util.ErrorHandler;

import java.io.IOException;

/**
 * @author dushougudu
 */
@Slf4j
public class MongoResetHandler implements ErrorHandler {

    private final LeaderLatch leaderLatch;

    MongoResetHandler(LeaderLatch leaderLatch) {
        this.leaderLatch = leaderLatch;
    }

    @Override
    public void handleError(Throwable t) {
        log.error("Unexpected error occurred while listening to MongoDB.", t);
        try {

            leaderLatch.close(LeaderLatch.CloseMode.NOTIFY_LEADER);
            leaderLatch.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
